package com.alipay.rebate.shop.utils;

import com.alipay.rebate.shop.exceptoin.TpwdGenerateFailException;
import com.alipay.rebate.shop.helper.AppSettingsHelper;
import com.alipay.rebate.shop.model.Product;
import com.alipay.rebate.shop.pojo.dingdanxia.*;
import com.alipay.rebate.shop.pojo.jd.JdOrdersRsp;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import com.google.gson.Gson;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.java2d.pipe.SpanClipRenderer;
import sun.reflect.generics.tree.Tree;

public class DingdanxiaUtil {

  private static Logger logger = LoggerFactory.getLogger(DingdanxiaUtil.class);
  public  final static String ADZONE_NAME = "渠道专属PID";
  public  final static String ADZONE_ID = "109205150467";
  public  final static String ADZONE_ID_ACTIVITY = "109207000047";
  private final static String APIKEY = "0TT6fg4Mk4OOmnf2pcaqWAlPhJKiRjbv";
  private final static String GET_PRIVILEGE_URL = "http://api.tbk.dingdanxia.com/tbk/id_privilege";
  private final static String SUPER_SEARCH_URL = "http://api.tbk.dingdanxia.com/tbk/super_search";
  private static final String ACTIVITY_PRODUCT_PID = "mm_196240035_620000087_109207000047";
  public static  String APPKEY = "27666797";
  public static  String APPSECRET = "d128f43ef975e70b4594699c53d0d9e7";
  public static final String RELATION_INVITOR_CODE = "H6HYGX";
  //private static final String tbAuthId = AppSettingsHelper.getTbAuthId();

  private final static String KEY = "b57733a7028b090109198ad4a3960e30a2ed1f5e701c2c90aeeabac616c1f8e9f4823b8aee6e09ea";

  static ObjectMapper objectMapper = new ObjectMapper();

  public static MeiTuanResponse getMeituanOrders(Integer startTime, Integer endTime,
                                                 String sid, Integer page, Integer pageSize) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/waimai/meituan_orders";
    Map<String,String> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    paraMap.put("sid",sid);
    paraMap.put("start_time",String.valueOf(startTime));
    paraMap.put("end_time",String.valueOf(endTime));
    paraMap.put("page",String.valueOf(page));
    paraMap.put("page_size",String.valueOf(pageSize));
    String sendGet = HttpUtils.sendPost(url, paraMap);
    return objectMapper.readValue(sendGet,MeiTuanResponse.class);
  }

  public static MeiTuanOrderResponse getMeituanOrderId(String orderid) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/waimai/meituan_orderid";
    Map<String,String> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    paraMap.put("orderid",orderid);
    String sendGet = HttpUtils.sendPost(url, paraMap);
    return objectMapper.readValue(sendGet,MeiTuanOrderResponse.class);
  }

  public static Object getMeituanPrivilege(String sid,String qrcode) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/waimai/meituan_privilege";
    Map<String,String> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    paraMap.put("sid",sid);
    paraMap.put("qrcode",qrcode);
    String sendGet = HttpUtils.sendPost(url, paraMap);
    return objectMapper.readValue(sendGet,Object.class);
  }

  static Gson gson = new Gson();

  public static Object  test() throws Exception {
    String url = "http://test.ujuec.com/gw";
    TreeMap<String,String> paraMap = new TreeMap<>();
    paraMap.put("appKey","E14V0pwyTZrJZAB9");
    paraMap.put("data",userInfo());
    paraMap.put("timestamp",String.valueOf(System.currentTimeMillis()));
    paraMap.put("sign",SignMD5Util.getSignStr(paraMap,"c07627d655f824fee49b0252d3b89595"));
    Object getObj = HttpUtils.sendGetTest(url,paraMap);
    return getObj;
  }
  private static String userInfo(){
    TreeMap<String,String> paraMap = new TreeMap<>();
    paraMap.put("uphone","18333051754");
    paraMap.put("user_name","test");
    paraMap.put("avatar",null);
    paraMap.put("money","5.70");
    paraMap.put("jifen","100");
    paraMap.put("agent_create_time",null);
    paraMap.put("alipay","18333051754");
    paraMap.put("alipay_name","test");
    paraMap.put("login_time","2019-09-16 18:30:49");
    paraMap.put("create_time","2019-09-16 18:30:49");
    paraMap.put("wx_unionid","ADDFVDDFDdf");
    paraMap.put("user_level","1");
    paraMap.put("agent_level","普通会员");
    String toJson = gson.toJson(paraMap);
    String base64Encode = SignMD5Util.base64Encode(toJson);
    return base64Encode;
  }
  //    paraMap.put("uphone","18333051754");
//    paraMap.put("user_name","test");
//    paraMap.put("avatar",null);
//    paraMap.put("money","5.70");
//    paraMap.put("jifen","100");
//    paraMap.put("agent_create_time",null);
//    paraMap.put("alipay","18333051754");
//    paraMap.put("alipay_name","test");
//    paraMap.put("login_time","2019-09-16 18:30:49");
//    paraMap.put("create_time","2019-09-16 18:30:49");
//    paraMap.put("wx_unionid","ADDFVDDFDdf");
//    paraMap.put("user_level","1");
//    paraMap.put("agent_level","普通会员");
  public static Object getPddUrlGenerate(String p_id_list) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/pdd/urlgenerate";
    Map<String,Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    paraMap.put("generate_short_url",true);
    paraMap.put("generate_mobile",true);
    paraMap.put("multi_group",false);
    paraMap.put("generate_weapp_webview",false);
    paraMap.put("we_app_web_view_short_url",true);
    paraMap.put("we_app_web_wiew_url",false);
    paraMap.put("channel_type",4);
    paraMap.put("p_id_list",p_id_list);
    String response = HttpUtils.sendGetObject(url, paraMap);
    Object obj = objectMapper.readValue(response, Object.class);

    return obj;
  }


  public static Object getPddUrlConvert(String source_url,String pid,Boolean generate_schema_url,String custom_parameters) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/pdd/url_convert";
    Map<String,Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
//    if (StringUtils.isEmpty("signature")){
//      paraMap.put("signature",req.getSignature());
//    }

//    if (StringUtils.isEmpty("source_url")){
      paraMap.put("source_url",source_url);
//    }
//    if (StringUtils.isEmpty("pid")){
      paraMap.put("pid",pid);
//    }
    if (StringUtils.isEmpty("custom_parameters")){
      paraMap.put("custom_parameters",custom_parameters);
    }
    if (generate_schema_url != null){
      paraMap.put("generate_schema_url",generate_schema_url);
    }
    String response = HttpUtils.sendGetObject(url, paraMap);
    Object obj = objectMapper.readValue(response, Object.class);

    return obj;
  }


  public static Object getJdGoodsCategory(Integer parentId,Integer grade) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/jd/goods_category";

    Map<String,Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);

    if (parentId != null){
      paraMap.put("parentId",parentId);
    }
    if (grade != null){
      paraMap.put("grade",grade);
    }
    String response = HttpUtils.sendGetObject(url, paraMap);
    Object obj = objectMapper.readValue(response, Object.class);

    return obj;
  }


  //获取拼多多订单信息
  public static PddOrdersRsp getPddOrders(Long startUpdateTime,Long endUpdateTime,Integer pageSize,Integer page) throws IOException {

    String url = "http://api.tbk.dingdanxia.com/pdd/orderlist";
    Map<String,Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);

    paraMap.put("start_update_time",startUpdateTime);
    paraMap.put("end_update_time",endUpdateTime);
    if (pageSize != null){
      paraMap.put("page_size",pageSize);
    }
    if (page != null){
      paraMap.put("page",page);
    }

    String responseBody = HttpUtils.sendGetObject(url,paraMap);
    PddOrdersRsp obj = objectMapper.readValue(responseBody,PddOrdersRsp.class);
    return obj;
  }


  //获取京东订单信息
  public static JdOrdersRsp getJdOrders(String time, Integer pageNo, Integer pageSize, Integer type, Long childUnionId) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/jd/order_details";
    Map<String, Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);

    paraMap.put("time",time);

    if (pageNo != null){
      paraMap.put("pageNo",pageNo);
    }
    if (pageSize != null){
      paraMap.put("pageSize",pageSize);
    }
    if (type != null){
      paraMap.put("type",type);
    }
    if (childUnionId != null){
      paraMap.put("childUnionId",childUnionId);
    }

    paraMap.put("key", KEY);

    String responseBody = HttpUtils.sendGetObject(url, paraMap);
    return objectMapper.readValue(responseBody,JdOrdersRsp.class);
  }


  public static Object getPddPidgenerate() throws IOException {
    String url = "http://api.tbk.dingdanxia.com/pdd/pidgenerate";
    Map<String, Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);

    paraMap.put("number",1);
    String responseBody = HttpUtils.sendGetObject(url,paraMap);

    Object obj = objectMapper.readValue(responseBody,Object.class);

    return obj;
  }


  public static Object getPddConvert(PddConvertReq req) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/pdd/convert";
    Map<String, Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    if(!StringUtils.isEmpty(req.getSignature())){
      paraMap.put("signature",req.getSignature());
    }
    if (!StringUtils.isEmpty(req.getCustom_parameters())){
      paraMap.put("custom_parameters",req.getCustom_parameters());
    }
    if(!StringUtils.isEmpty(req.getGoods_id_list())){
      paraMap.put("goods_id_list",req.getGoods_id_list());
    }
    if (!StringUtils.isEmpty(req.getZs_duo_id())){
      paraMap.put("zs_duo_id",req.getZs_duo_id());
    }

    if (!StringUtils.isEmpty(req.getP_id())){
      paraMap.put("p_id",req.getP_id());
    }

    if (req.getGenerate_short_url() != null){
      paraMap.put("generate_short_url",req.getGenerate_short_url());
    }
    if (req.getGenerate_we_app() != null){
      paraMap.put("generate_we_app",req.getGenerate_we_app());
    }
    if (req.getGenerate_weapp_webview() != null){
      paraMap.put("generate_weapp_webview",req.getGenerate_weapp_webview());
    }
    if (req.getGenerate_weiboapp_webview() != null){
      paraMap.put("generate_weiboapp_webview",req.getGenerate_weiboapp_webview());
    }
    if (req.getMulti_group() != null){
      paraMap.put("multi_group",req.getMulti_group());
    }
    paraMap.put("generate_schema_url",true);
    String responseBody = HttpUtils.sendGetObject(url,paraMap);
    logger.debug("req.getCustom_parameters() is : {}",req.getCustom_parameters());
    Object obj = objectMapper.readValue(responseBody,Object.class);

    return obj;

  }



  public static Object getPddGoodsListReq(PddGoodsListReq req) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/pdd/goodslist";
    Map<String, Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    //paraMap.put("tb_auth_id ",tbAuthId);
    if(!StringUtils.isEmpty(req.getSignature())){
      paraMap.put("signature",req.getSignature());
    }
    if(!StringUtils.isEmpty(req.getP_id())){
      paraMap.put("p_id",req.getP_id());
    }
    if(req.getLimit() != null){
      paraMap.put("limit",req.getLimit());
    }
    if (req.getOffset() != null){
      paraMap.put("offset",req.getOffset());
    }
    if (req.getSort_type() != null){
      paraMap.put("sort_type",req.getSort_type());
    }
    String responseBody = HttpUtils.sendGetObject(url,paraMap);

    Object obj = objectMapper.readValue(responseBody,Object.class);

    return obj;

  }

  public static Object getPddGoodesDetail(PddGoodsDetailReq req) throws IOException {
    logger.debug("req is : {}",req);
    String url = "http://api.tbk.dingdanxia.com/pdd/goods_detail";
    Map<String, Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    if(!StringUtils.isEmpty(req.getSignature())){
      paraMap.put("signature",req.getSignature());
    }
    if(!StringUtils.isEmpty(req.getCustom_parameters())){
      paraMap.put("custom_parameters",req.getCustom_parameters());
    }
    if(!StringUtils.isEmpty(req.getPid())){
      paraMap.put("pid",req.getPid());
    }
    if(!StringUtils.isEmpty(req.getSearch_id())){
      paraMap.put("search_id",req.getSearch_id());
    }
    if(req.getGoods_id_list() != null){
      paraMap.put("goods_id_list",req.getGoods_id_list());
    }
    if(req.getPlan_type() != null){
      paraMap.put("plan_type",req.getPlan_type());
    }
    if(req.getZs_duo_id() != null){
      paraMap.put("zs_duo_id",req.getZs_duo_id());
    }

    String responseBody = HttpUtils.sendGetObject(url,paraMap);

    Object obj = objectMapper.readValue(responseBody,Object.class);

    return obj;

  }

  public static Object getPddGoodsSearch(PddGoodsSearchReq req) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/pdd/goods_search";
    Map<String, Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    if(!StringUtils.isEmpty(req.getSignature())){
      paraMap.put("signature",req.getSignature());
    }
    if(!StringUtils.isEmpty(req.getKeyword())){
      paraMap.put("keyword",req.getKeyword());
    }
    if(!StringUtils.isEmpty(req.getGoods_id_list())){
      paraMap.put("goods_id_list",req.getGoods_id_list());
    }
    if(!StringUtils.isEmpty(req.getRange_list())){
      paraMap.put("range_list",req.getRange_list());
    }
    if(!StringUtils.isEmpty(req.getPid())){
      paraMap.put("pid",req.getPid());
    }
    if(!StringUtils.isEmpty(req.getCustom_parameters())){
      paraMap.put("custom_parameters",req.getCustom_parameters());
    }

    if(req.getOpt_id() != null){
      paraMap.put("opt_id",req.getOpt_id());
    }

    if(req.getPage() != null){
      paraMap.put("page",req.getPage());
    }

    if(req.getPage_size() != null){
      paraMap.put("page_size",req.getPage_size());
    }

    if(req.getSort_type() != null){
      paraMap.put("sort_type",req.getSort_type());
    }

    if(req.getCat_id() != null){
      paraMap.put("cat_id",req.getCat_id());
    }

    if(req.getWith_coupon() != null){
      paraMap.put("with_coupon",req.getWith_coupon());
    }

    if(req.getMerchant_type() != null){
      paraMap.put("merchant_type",req.getMerchant_type());
    }

    if(req.getMerchant_type_list() != null){
      paraMap.put("merchant_type_list",req.getMerchant_type_list());
    }

    if(req.getIs_brand_goods() != null){
      paraMap.put("is_brand_goods",req.getIs_brand_goods());
    }

    if(req.getActivity_tags() != null){
      paraMap.put("activity_tags",req.getActivity_tags());
    }


    String responseBody = HttpUtils.sendGetObject(url,paraMap);

    Object obj = objectMapper.readValue(responseBody,Object.class);

    return obj;

  }


  public static Object getApitj(String signature) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/user/get_apitj";
    Map<String, String> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    if(!StringUtils.isEmpty(signature)){
      paraMap.put("signature",signature);
    }

    String responseBody = HttpUtils.sendGet(url, paraMap);
    Object readValue = objectMapper.readValue(responseBody, Object.class);
    return readValue;

  }


  public static Object getByUnionidPromotionTwo(ByUnionidPromotionTwo req) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/jd/by_unionid_promotion";
    Map<String, Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    if(!StringUtils.isEmpty(req.getSignature())){
      paraMap.put("signature",req.getSignature());
    }
    if (!StringUtils.isEmpty(req.getCouponUrl())){
      paraMap.put("couponUrl",req.getCouponUrl());
    }
    if (!StringUtils.isEmpty(req.getMaterialId())){
      paraMap.put("materialId",req.getMaterialId());
    }
    if (!StringUtils.isEmpty(req.getPid())){
      paraMap.put("pid",req.getPid());
    }
    if (!StringUtils.isEmpty(req.getSubUnionId())){
      paraMap.put("materialId",req.getMaterialId());
    }
    if (req.getChainType() != null){
      paraMap.put("chainType",req.getChainType());
    }
    if (req.getPositionId() != null){
      paraMap.put("positionId",req.getPositionId());
    }
    paraMap.put("unionId",AppSettingsHelper.getUnionId());

    String responseBody = HttpUtils.sendGetObject(url,paraMap);
    Object obj = objectMapper.readValue(responseBody,Object.class);
    return obj;
  }

  public static Object getByUnionidPromotion(ByUnionidPromotionReq req) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/jd/by_unionid_promotion";
    Map<String, Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    if(!StringUtils.isEmpty(req.getSignature())){
      paraMap.put("signature",req.getSignature());
    }
    if (!StringUtils.isEmpty(req.getCouponUrl())){
      paraMap.put("couponUrl",req.getCouponUrl());
    }
    if (!StringUtils.isEmpty(req.getMaterialId())){
      paraMap.put("materialId",req.getMaterialId());
    }
    if (!StringUtils.isEmpty(req.getPid())){
      paraMap.put("pid",req.getPid());
    }
    if (!StringUtils.isEmpty(req.getSubUnionId())){
      paraMap.put("materialId",req.getMaterialId());
    }
    if (req.getChainType() != null){
      paraMap.put("chainType",req.getChainType());
    }
    if (req.getPositionId() != null){
      paraMap.put("positionId",req.getPositionId());
    }
    if (req.getUnionId() != null){
      paraMap.put("unionId",req.getUnionId());
    }

    String responseBody = HttpUtils.sendGetObject(url,paraMap);
    Object obj = objectMapper.readValue(responseBody,Object.class);
    return obj;
  }


  //创建推广位
  public static DingdanxiaRsp<CreatePositionRsp> getCreatePosition(String spaceNameList) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/jd/create_position";
    Map<String, Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    paraMap.put("unionId",AppSettingsHelper.getUnionId());
    paraMap.put("key",AppSettingsHelper.getJdKey());
    paraMap.put("siteId",AppSettingsHelper.getSiteId());
    paraMap.put("unionType",1);
    paraMap.put("type",2);
    paraMap.put("spaceNameList",spaceNameList);
    String responseBody = HttpUtils.sendGetObject(url,paraMap);
    return objectMapper.readValue(responseBody,new TypeReference<DingdanxiaRsp<CreatePositionRsp>>(){});
  }

  public static Object getActivityLink(ActivityLinkReq req) throws Exception {
    String url = "http://api.tbk.dingdanxia.com/tbk/activitylink";
    Map<String, String> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);

    //paraMap.put("tb_auth_id ",tbAuthId);

    if(!StringUtils.isEmpty(req.getSignature())){
      paraMap.put("signature",req.getSignature());
    }
    paraMap.put("promotion_scene_id",req.getPromotion_scene_id());

    if (!StringUtils.isEmpty(req.getRelation_id())){
      paraMap.put("relation_id",req.getRelation_id());
    }
    if (!StringUtils.isEmpty(req.getUnion_id())){
      paraMap.put("union_id",req.getUnion_id());
    }
    if (req.getPlatform() != null){
      paraMap.put("platform",String.valueOf(req.getPlatform()));
    }

    String responseBody = HttpUtils.sendGet(url,paraMap);
    Object obj = objectMapper.readValue(responseBody,Object.class);
    return obj;
  }


  public static Object getTklCreateTwo(TklCreateTwoReq req) throws Exception {
    String url = "http://api.tbk.dingdanxia.com/tkl/create2";
    Map<String, String> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    if(!StringUtils.isEmpty(req.getSignature())){
      paraMap.put("signature",req.getSignature());
    }
    if (!StringUtils.isEmpty(req.getUrl())) {
      paraMap.put("url", req.getUrl());
    }

    if (!StringUtils.isEmpty(req.getLogo())){
      paraMap.put("logo",req.getLogo());
    }
    if (!StringUtils.isEmpty(req.getText())){
      paraMap.put("text",req.getText());
    }

    TreeMap<String,String> map = new TreeMap<>();
    map.put("url",req.getUrl());
    map.put("logo",req.getLogo());
    map.put("text",req.getText());

    String sign = sign(map);

    logger.debug("sign is : {}",sign);

    if (!req.getSalt().equals(sign)){
      logger.debug(" fail req.getSalt is : {}",req.getSalt());
      logger.debug("fail sign is : {}",sign);
      throw new RuntimeException("淘口令生成失败");
    }

    String responseBody = HttpUtils.sendPost(url,paraMap);
    Object obj = objectMapper.readValue(responseBody,Object.class);
    return obj;

  }

  public static Object getQueryJingfenGoods(QueryJingfenGoodsReq req) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/jd/query_jingfen_goods";
    Map<String, Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    if(!StringUtils.isEmpty(req.getSignature())){
      paraMap.put("signature",req.getSignature());
    }
    if (!StringUtils.isEmpty(req.getSort())){
      paraMap.put("sort",req.getSort());
    }
    if (!StringUtils.isEmpty(req.getSortName())){
      paraMap.put("sortName",req.getSortName());
    }
    if (req.getEliteId() != null){
      paraMap.put("eliteId",req.getEliteId());
    }
    if (req.getPageIndex() != null){
      paraMap.put("pageIndex",req.getPageIndex());
    }
    if (req.getPageSize() != null){
      paraMap.put("pageSize",req.getPageSize());
    }
    String responseBody = HttpUtils.sendGetObject(url,paraMap);
    Object obj = objectMapper.readValue(responseBody,Object.class);
    return obj;
  }




  public static Object getQueryGoods(DingdanxiaQueryGoodsReq req) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/jd/query_goods";
    Map<String, Object> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    if(!StringUtils.isEmpty(req.getSignature())){
      paraMap.put("signature",req.getSignature());
    }
    if (!StringUtils.isEmpty(req.getKeyword())){
      paraMap.put("keyword",req.getKeyword());
    }
    if (!StringUtils.isEmpty(req.getOwner())){
      paraMap.put("owner",req.getOwner());
    }
    if (!StringUtils.isEmpty(req.getSortName())){
      paraMap.put("sortName",req.getSortName());
    }
    if (!StringUtils.isEmpty(req.getSort())){
      paraMap.put("sort",req.getSort());
    }
    if (!StringUtils.isEmpty(req.getBrandCode())){
      paraMap.put("brandCode",req.getBrandCode());
    }
    if (!StringUtils.isEmpty(req.getSkuIds())){
      paraMap.put("skuIds",req.getSkuIds());
    }
    if (req.getCid1() != null){
      paraMap.put("cid1",req.getCid1());
    }
    if (req.getCid2() != null){
      paraMap.put("cid2",req.getCid2());
    }
    if (req.getCid3() != null){
      paraMap.put("cid3",req.getCid3());
    }
    if (req.getCommissionShareEnd() != null){
      paraMap.put("commissionShareEnd",req.getCommissionShareEnd());
    }
    if (req.getCommissionShareStart() != null){
      paraMap.put("commissionShareStart",req.getCommissionShareStart());
    }
    if (req.getIsCoupon() != null){
      paraMap.put("isCoupon",req.getIsCoupon());
    }
    if (req.getIsHot() != null){
      paraMap.put("isHot",req.getIsHot());
    }
    if (req.getIsPG() != null){
      paraMap.put("isPG",req.getIsPG());
    }
    if (req.getPageIndex() != null){
      paraMap.put("pageIndex",req.getPageIndex());
    }
    if (req.getPageSize() != null){
      paraMap.put("pageSize",req.getPageSize());
    }
    if (req.getShopId() != null){
      paraMap.put("shopId",req.getShopId());
    }
    if (req.getPriceto() != null){
      paraMap.put("priceto",req.getPriceto());
    }
    if (req.getPricefrom() != null){
      paraMap.put("pricefrom",req.getPricefrom());
    }
    if (req.getPingouPriceStart() != null){
      paraMap.put("pingouPriceStart",req.getPingouPriceStart());
    }
    if (req.getPingouPriceEnd() != null){
      paraMap.put("pingouPriceEnd",req.getPingouPriceEnd());
    }


    String responseBody = HttpUtils.sendGetObject(url,paraMap);
    Object obj = objectMapper.readValue(responseBody,Object.class);
    return obj;

  }

  public static Object getQueryGoodsPromotioninfo(String signature,String skuIds) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/jd/query_goods_promotioninfo";
    Map<String, String> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    if(!StringUtils.isEmpty(signature)){
      paraMap.put("signature",signature);
    }
    if (!StringUtils.isEmpty(skuIds)){
      paraMap.put("skuIds",skuIds);
    }
    String responseBody = HttpUtils.sendPost(url, paraMap);
    return objectMapper.readValue(responseBody,Object.class);

  }



  public static Object tklQuery(String tkl,String signature) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/tkl/query";
    Map<String, String> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    if(!StringUtils.isEmpty(tkl)){
      paraMap.put("tkl",tkl);
    }
    if(!StringUtils.isEmpty(signature)){
      paraMap.put("signature",signature);
    }
    String responseBody = HttpUtils.sendPost(url,paraMap);
    Object obj = objectMapper.readValue(responseBody,Object.class);
    return obj;
  }

  public static DingdanxiaRsp<TklCreateRsp> tklCreate(TklCreateReq req)  {
    try {
      String url = "http://api.tbk.dingdanxia.com/tkl/create";
      Map<String,String> paraMap = new HashMap<>();
      paraMap.put("apikey",APIKEY);
      ReflectUtil.buildParaMap(paraMap,req);
      String responseBody = HttpUtils.sendPost(url,paraMap);
      return objectMapper.readValue(responseBody,new TypeReference<DingdanxiaRsp<TklCreateRsp>>(){});
    }catch (Exception ex){
      logger.debug("create tpwd failed, {}",ex);
      throw new TpwdGenerateFailException(ex.getMessage());
    }
  }


  public static Object itemInfo(String signature, String num_iids, Integer platform) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/tbk/item_info";
    Map<String, String> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    if(!StringUtils.isEmpty(num_iids)){
      paraMap.put("num_iids",num_iids);
    }
    if(!StringUtils.isEmpty(signature)){
      paraMap.put("signature",signature);
    }
    if(platform != null){
      paraMap.put("platform",String.valueOf(platform));
    }
    String responseBody = HttpUtils.sendPost(url,paraMap);
    return objectMapper.readValue(responseBody,Object.class);
  }

  public static Object tkQrcode(TkQrcodeReq req) throws Exception {
    String url = "http://api.tbk.dingdanxia.com/tbk/tk_qrcode";
    return sendAndGetObj(url,req);
  }

  public static Object idPrivilege(IdPrivilegeReq request) throws Exception {
    if(request == null){
      return null;
    }
    String url = "http://api.tbk.dingdanxia.com/tbk/id_privilege";

    //request.setTb_auth_id(tbAuthId);
    return sendAndGetObj(url,request);
  }

  public static Object tklPrivilege(TklPrivilegeReq req) throws Exception {
    String url = "http://api.tbk.dingdanxia.com/tbk/tkl_privilege";
    //req.setTb_auth_id(tbAuthId);
    return sendAndGetObj(url,req);
  }

  public static DingdanxiaRsp<DingdanxiaLink> getPrivilegeLink(String goodsId, String relationId){
    try {
      Map<String, String> paraMap = new HashMap<>();
      paraMap.put("apikey",APIKEY);
      paraMap.put("id",goodsId);
//      if (relationId != null) {
//        paraMap.put("relation_id", relationId);
//      }
      paraMap.put("pid",AppSettingsHelper.getPid());
      String responseBody = HttpUtils.sendPost(GET_PRIVILEGE_URL,paraMap);
      logger.debug("getPrivilegeLink dingdanxia response:{}",responseBody);
      ObjectMapper objectMapper = new ObjectMapper();
      DingdanxiaRsp<DingdanxiaLink> dingdanxiaRsp =
          objectMapper.readValue(responseBody,new TypeReference<DingdanxiaRsp<DingdanxiaLink>>(){});
      return dingdanxiaRsp;
    } catch (IOException e) {
      logger.debug("ex is : {}",e.getMessage());
      return null;
    }
  }

  public static DingdanxiaRsp<DingdanxiaLink> getAcvitityProductPrivilegeLink(String goodsId){
    try {
      Map<String, String> paraMap = new HashMap<>();
      paraMap.put("apikey",APIKEY);
      paraMap.put("id",goodsId);
      paraMap.put("pid", AppSettingsHelper.getActivityPid());
      String responseBody = HttpUtils.sendPost(GET_PRIVILEGE_URL,paraMap);
      logger.debug("getAcvitityProductPrivilegeLink dingdanxia response:{}",responseBody);
      ObjectMapper objectMapper = new ObjectMapper();
      DingdanxiaRsp<DingdanxiaLink> dingdanxiaRsp =
          objectMapper.readValue(responseBody,new TypeReference<DingdanxiaRsp<DingdanxiaLink>>(){});
      return dingdanxiaRsp;
    } catch (IOException e) {
      logger.debug("ex is : {}",e.getMessage());
      return null;
    }
  }

  public static Object superSearch(SuperSearchReq request) throws Exception{
    if(request == null){
      return null;
    }
    Object obj =  sendAndGetObj(SUPER_SEARCH_URL,request);
    String body = objectMapper.writeValueAsString(obj);
    logger.debug("body is : {}",body);
    Map<String,Object> map = objectMapper.readValue(body,Map.class);
    //logger.debug("tb_auth_id is : {}",tbAuthId);
    //map.put("tb_auth_id ",tbAuthId);

    logger.debug("map is : {}",map);
    String code = map.get("code").toString();
    logger.debug("code is : {}",code);
    if("-1".equals(code)){
      logger.debug("second time to send request");
      Object data = map.get("data");
      logger.debug("data is : {}",data);
      if(data != null){
        String subBody = objectMapper.writeValueAsString(data);
        logger.debug("subBody is : {}",subBody);
        Map<String,Object> dataMap = objectMapper.readValue(subBody,Map.class);
        String subCode = dataMap.get("code").toString();
        logger.debug("subCode:{}",subCode);
        if("15".equals(subCode)){
          obj =  sendAndGetObj(SUPER_SEARCH_URL,request);
        }
      }
    }
    return obj;
  }


//  public static Object spkOptimus(OptimusReq req) throws Exception {
//    String url = "http://api.tbk.dingdanxia.com/spk/optimus";
//    Map<String,String> paraMap = new HashMap<>();
//    ReflectUtil.buildParaMap(paraMap,req);
//    paraMap.put("apikey",APIKEY);
//    logger.debug("spkOptimus search paraMap is : {}",paraMap);
//    String responseBody = HttpUtils.sendPost(url,paraMap);
//    logger.debug("spkOptimus responseBody is : {}",responseBody);
//    Object rsp = objectMapper.readValue(responseBody, Object.class);
//    logger.debug("DingdanxiaOptimusProduct rsp is : {}",rsp);
//    return rsp;
//  }

  public static List<Product> spkOptimus(OptimusReq req) throws Exception {
    String url = "http://api.tbk.dingdanxia.com/spk/optimus";
    Map<String,String> paraMap = new HashMap<>();
    ReflectUtil.buildParaMap(paraMap,req);
    paraMap.put("apikey",APIKEY);
    logger.debug("spkOptimus search paraMap is : {}",paraMap);
    String responseBody = HttpUtils.sendPost(url,paraMap);
    logger.debug("spkOptimus responseBody is : {}",responseBody);
    SpkOptimusResponse rsp = objectMapper.readValue(responseBody, SpkOptimusResponse.class);
    logger.debug("DingdanxiaOptimusProduct rsp is : {}",rsp);
    List<DingdanxiaOptimusProduct> optimusProducts = rsp.getData();
    logger.debug("optimusProducts is : {}",optimusProducts);
    return convertOptimusProductList2ProductList(optimusProducts);

  }

  public static Object couponSearch(String signature, String id) throws IOException {
    String url = "http://api.tbk.dingdanxia.com/tbk/coupon_search";
    Map<String,String> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    if(!StringUtils.isEmpty(signature)){
      paraMap.put("signature",signature);
    }
    paraMap.put("id",id);
    //paraMap.put("tb_auth_id ",tbAuthId);
    String responseBody = HttpUtils.sendPost(url,paraMap);
    return objectMapper.readValue(responseBody,Object.class);
  }

  private static Object sendAndGetObj(String url, Object request)throws Exception{
    Map<String, String> paraMap = new HashMap<>();
    paraMap.put("apikey",APIKEY);
    paraMap.put("appsecret",APPSECRET);
    ReflectUtil.buildParaMap(paraMap,request);
    logger.debug("super search paraMap is : {}",paraMap);
    String responseBody = HttpUtils.sendPost(url,paraMap);
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.readValue(responseBody,Object.class);
  }

  private static String HTTP_PREFIX = "http:";

  private static List<Product> convertOptimusProductList2ProductList(List<DingdanxiaOptimusProduct> optimusProducts){

    logger.debug("convertOptimusProductList2ProductList is : {}",optimusProducts);
    List<Product> products = new ArrayList<>();
    if(ListUtil.isEmptyList(optimusProducts)){
      return products;
    }
    optimusProducts.forEach(optimusProduct -> {
      Product product = covertOptimusProduct2Product(optimusProduct);
      products.add(product);
    });
    return products;
  }

  private static Product covertOptimusProduct2Product(DingdanxiaOptimusProduct optimusProduct){
    logger.debug("covertOptimusProduct2Product");
    if(optimusProduct == null) return null;
    Product product = new Product();
    // goodsId
    product.setGoodsId(optimusProduct.getItem_id());
    // itemLink
    if(!StringUtils.isEmpty(optimusProduct.getClick_url())){
      product.setItemLink(optimusProduct.getClick_url());
      if(!optimusProduct.getClick_url().startsWith(HTTP_PREFIX)){
        product.setItemLink(HTTP_PREFIX + optimusProduct.getClick_url());
      }
    }
    // title
    product.setTitle(optimusProduct.getTitle());
    // dtitle
    product.setDtitle(optimusProduct.getShort_title());
    // description
    product.setDescription(optimusProduct.getItem_description());
    // cid
    product.setCid(optimusProduct.getCategory_id());
    // tbcid
    product.setTbcid(optimusProduct.getLevel_one_category_id());
    // mainPic
    if(!StringUtils.isEmpty(optimusProduct.getPict_url())){
      product.setMainPic(optimusProduct.getPict_url());
      if(!optimusProduct.getPict_url().startsWith(HTTP_PREFIX)){
        product.setMainPic(HTTP_PREFIX + optimusProduct.getPict_url());
      }
    }
    // product.setMarketingMainPic();
    product.setShopType(optimusProduct.getUser_type());

    // originalPrice
    if(!StringUtils.isEmpty(optimusProduct.getOrig_price())){
      product.setOriginalPrice(new BigDecimal(optimusProduct.getOrig_price()));
    }
    // actualPrice
    product.setActualPrice(optimusProduct.getZk_final_price());
    product.setOriginalPrice(optimusProduct.getZk_final_price());
    if(optimusProduct.getCoupon_amount() != null){
      BigDecimal b2 = new BigDecimal(optimusProduct.getCoupon_amount());
      product.setOriginalPrice(product.getActualPrice().add(b2));
    }
    // discounts
    // commissionType

    // commissionRate
    product.setCommissionRate(optimusProduct.getCommission_rate());

    // couponLink
    if(!StringUtils.isEmpty(optimusProduct.getCoupon_click_url())){
      product.setCouponLink(optimusProduct.getCoupon_click_url());
      if(!optimusProduct.getCoupon_click_url().startsWith(HTTP_PREFIX)){
        product.setCouponLink(HTTP_PREFIX + optimusProduct.getCoupon_click_url());
      }
    }
    // couponTotalNum
    product.setCouponTotalNum(optimusProduct.getCoupon_total_count());
    if(optimusProduct.getCoupon_total_count() != null &&
        optimusProduct.getCoupon_remain_count() != null){
      Integer receivedNum = optimusProduct.getCoupon_total_count() - optimusProduct.getCoupon_remain_count();
      // couponReceiveNum
      product.setCouponReceiveNum(receivedNum);
    }
    // couponEndTime
    product.setCouponEndTime(optimusProduct.getCoupon_end_time());
    // couponStartTime
    product.setCouponStartTime(optimusProduct.getCoupon_start_time());
    // couponPrice
    if(optimusProduct.getCoupon_amount() != null){
      product.setCouponPrice(new BigDecimal(optimusProduct.getCoupon_amount()));
    }
    // couponConditions
    product.setCouponConditions(optimusProduct.getCoupon_start_fee());
    // monthSales
    product.setMonthSales(optimusProduct.getVolume());
    // twoHoursSales
    // dailySales
    // brand
    // brandId
    // brandName
    // createTime
    // tchaoshi
    // activityType
    // activityStartTime
    // activityEndTime

    product.setSellerId(optimusProduct.getSeller_id());
    product.setShopName(optimusProduct.getNick());
    return product;
  }

  private static String TOKEN = "SASDADSDDDFFFDGHGJHGFDVV";

  private static String sign(TreeMap<String,String> map){

    logger.debug("map is : {}",map);

    List<String> keySet = new ArrayList<>();
    keySet.add("url");
    keySet.add("logo");
    keySet.add("text");

    String kv = "";
    for (String key : keySet){
      kv += key+"="+map.get(key)+"&";
    }
    kv = kv + "token="+TOKEN;

    logger.debug("kv is : {}",kv);

    String encrypt = md5(kv);

    return encrypt;
  }

  public static String md5(String res){
    //加密后的字符串
    return DigestUtils.md5Hex(res);
  }



//  public static void main(String args[]) throws Exception {
//    OptimusReq optimusReq = new OptimusReq();
//    optimusReq.setMaterial_id(3756);
//    List<Product> rsp3 = spkOptimus(optimusReq);
//    System.out.println(rsp3);
//
//    String s1 = "https://s.click.taobao.com/t?e=m%3D2%26s%3Dylpj0KvEgYMcQipKwQzePCperVdZeJviyK8Cckff7TVRAdhuF14FMYt%2BAsQw8Tv88sviUM61dt3apadhk1iGsnqecEGdgXUgkyh5JXN9iUJCZ9Qz7deVfkCJLLTQlBsuu3ex8PaaVqDLP4XO97Tuip7xDSuPmzLWC2TKqEFvn7gehppSckYlU8tA8Qks8BYBXdZXtfxfyx3zdr7%2FDGtBCRfZNZ%2Fo%2BZPLzueC0P1cNS%2B6zThPYvErzhJBFs1%2FyLxVPxey8%2Bhd8pyvTW5l3DCD33WHtde0jnhWuBURhOzFBCBs6ee4R2%2FAhJ8XaY204ddbUxv2dyXuB4Xw%2FA6QPi6Vl7DyBIHyflexwMiViNi%2F7tesOrQhP3QTompdkxRfuqxxEkDdWE7kR3s6%2FcbGes9r9yGFCzYOOqAQ&pvid=24894679&union_lens=lensId:0b175abc_0cbc_171ab776bf8_631d";
//    String s2 = "";
//    System.out.println(s1.equals(s2));
//
//
//
//  }


}
